package com.epfresh.utils;

import android.content.Context;
import android.os.Environment;
import android.util.Base64;
import android.util.Log;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.Map;

public class FileCache {
	private static final String TAG = FileCache.class.getName();
    public static final String WHOLESALE_CONV = ".dat";
    private Context mContext;
	 
    public FileCache(Context context) {
    	mContext = context.getApplicationContext();
    }

    /** 获得缓存目录 **/
    public String getCachePath() {
    	String cachePath = null;
        boolean sdCardExist = Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED);  //判断sd卡是否存在
        
        if (sdCardExist) {
        	cachePath = Environment.getExternalStorageDirectory()+ "/Android/data/"+mContext.getPackageName()+"/cache/";
        }else{
        	cachePath =  mContext.getCacheDir().getAbsolutePath()+"/cache/";
        	Log.d(TAG, "zz getCachePath no sdcard path =" + cachePath);
        }
        
        File file = new File(cachePath);
        if(!file.exists()){
        	file.mkdirs();
        }
        
        return cachePath;
    } 
    /**
     * 判断文件是否过时
     * @param url
     * @param expiredTime
     * @return true:已过时， false：未过时
     */
    public boolean isExpired(String url, Map<String, String> map, long expiredTime){
    	String filename = getCachePath() + getCacheDecodeString(url, map);
    	File file = new File(filename);
    	
    	if (file.exists() && file.isFile()) {
    		 long expired = System.currentTimeMillis() - file.lastModified();
    		 
         	Log.d(TAG, "zz isExpired url=" + url + " expired=" + expired);
         	
    		 if(expired <= expiredTime)
    			 return false;
    	}
    	
    	return true;
    }
    
    /**
     * 获取缓存文件内容
     * @param url
     * @return
     */
    public String getUrlCache(String url, Map<String, String> map) {
        if (url == null || "".equals(url)) {
        	Log.d(TAG, "zz getUrlCache url is null");
            return null;
        }
        
        String filename = getCachePath() + getCacheDecodeString(url, map);
        return readFile(filename);
    }
 
    /**
     * 保存内容到缓存文件
     * @param data
     * @param url
     */
    public void setUrlCache(String data, String url, Map<String, String> map) {
        if (url == null || "".equals(url)) {
        	Log.d(TAG, "zz setUrlCache url is null");
        	return;
        }
        
        String filename = getCachePath() + getCacheDecodeString(url, map);
       
        saveFile(filename, data);
    }
 
    private String getCacheDecodeString(String url, Map<String, String> map) {
    	String filename = null;
        //1. 处理特殊字符
        //2. 去除后缀名带来的文件浏览器的视图凌乱(特别是图片更需要如此类似处理，否则有的手机打开图库，全是我们的缓存图片)
        if (url != null) {
        	filename = url.replaceAll("[.:/,%?&=]", "+").replaceAll("[+]+", "_");
        }
        
        if (map != null && !map.isEmpty()) {
			for (Map.Entry<String, String> entry : map.entrySet()) {
				// 解析Map传递的参数，使用一个键值对对象BasicNameValuePair保存。
				filename +="_"+entry.getKey()+"_"+entry.getValue();
			}
		}
        
        filename += WHOLESALE_CONV;
        
        return filename;
    }
    
    /**
	 * Save file
	 * @param filename file name
	 * @param content file content
	 */
    public void saveFile(final String filename, final String content) {
		new Thread() {
			@Override
			public void run() {
				FileOutputStream os = null;
				OutputStreamWriter osw = null;
				BufferedWriter bw = null;
				try {
					os = new FileOutputStream(filename);
					osw = new OutputStreamWriter(os);
					bw = new BufferedWriter(osw);
					String str = Base64.encodeToString(content.getBytes(), Base64.DEFAULT);
					bw.write(str);
				} catch (Exception e) {
					e.printStackTrace();
				} finally {
					try {
						if (bw != null) {
							bw.flush();
						}
						
						if (osw != null) {
							osw.flush();
						}
						
						if(bw!=null){
							bw.close();
						}
						
						if(osw!=null){
							osw.close();
						}
						
						if(os!=null){
							os.close();
						}
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}
		}.start();
	}
	
	/**
	 * Read file
	 * @param filename
	 * @return
	 */
	public String readFile(String filename) {
		FileInputStream is = null;
		InputStreamReader isr = null;
		BufferedReader br = null;
		File file = new File(filename);
		
		if (!file.exists()) {
			return null;
		}
		
		StringBuilder res = new StringBuilder();
		try {
			is = new FileInputStream(filename);
			isr = new InputStreamReader(is);
			br = new BufferedReader(isr);
//			String temp = null;
//			while ((temp = br.readLine()) != null) {
//				res.append(temp);
//			}
			int len = 0;
			char[] buf = new char[1024];
			while((len = br.read(buf, 0, 1024)) > 0){
				res.append(buf, 0, len);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				br.close();
				isr.close();
				is.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		
		return new String(Base64.decode(res.toString(), Base64.DEFAULT));
	}
	
}
